package com.yan.oss.service.impl;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.yan.oss.service.OssService;
import com.yan.oss.utils.ConstantPropertiesUtil;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
    @Override
    public String upLoadFileAvatar(MultipartFile file) {
        //获取阿里云存储相关常量
        String endpoint = ConstantPropertiesUtil.END_POINT;
        String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;


    try{

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

    // 上传文件流。
        InputStream inputStream =file.getInputStream();
        String fileName = file.getOriginalFilename();
        String uuid = UUID.randomUUID().toString().replaceAll("-","");
        fileName=uuid+fileName;
        String datepath = new DateTime().toString("yyyy/MM/dd");
        fileName=datepath+"/"+fileName;
        ossClient.putObject(bucketName, fileName, inputStream);
        // 关闭OSSClient。
        ossClient.shutdown();

//        https://yan-edu-1010.oss-cn-hangzhou.aliyuncs.com/6%20-%20What%20If%20I%20Want%20to%20Move%20Faster.mp4
        String url="https://"+bucketName+"."+endpoint+"/"+fileName;
        return url;


    }catch(Exception e){// 创建OSSClient实例。

       e.printStackTrace();
        return null;
    }



    }
}
